import React from 'react';
import PropTypes from 'prop-types';
import getCommentsList from '../../../request/get_comment_list';
import deleteComment from '../../../request/delete_comment';
import MyCommentsItem from './my_comments_item';
import Pagination from '../../../components/pagination/index';
import './index.scss'

class MyComments extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      page: 1,
      commentsList: [],
      hasComments: true,
    }
    this.deleteComment = this.deleteComment.bind(this)
    this.changePage = this.changePage.bind(this)
  }
  componentDidMount() {
    this.getComments()
  }
  // 获取我的评论
  getComments() {
    // 参数
    const params = {
      page: this.state.page,
      per_page: this.props.perPage,
      author: this.props.userInfo.user_id,
    }
    // 请求数据
    getCommentsList(params).then((res) => {
      const json = res.data
      if (json && json.length) {
        this.setState({
          commentsList: json,
          totalCount: json[0].total_count,
        })
      } else {
        this.setState({
          hasComments: false,
        })
      }
    }).catch(() => {

    })
  }
  // 点击改变分页
  changePage(index) {
    this.setState({
      page: index,
      commentsList: [],
    }, () => this.getComments())
  }
  // 删除评论
  deleteComment(id) {
    if (window.confirm('确定要删除此评论吗')) {
      deleteComment(id, {}).then(() => {
        this.getComments();
      })
    }
  }
  render() {
    const isPagination = this.state.totalCount > this.props.perPage;
    return (
      <div className="my-comments">
        {this.state.hasComments ?
          this.state.commentsList.length ? this.state.commentsList.map(item => (
            <MyCommentsItem data={item} key={item.id} deleteComment={this.deleteComment} />
          ))
            :
          <div className="loading">
              加载中...
          </div>
          :
          <div className="none">
            你还没有任何评论...
          </div>
        }
        {isPagination ? <Pagination pageSize={this.props.perPage} current={this.state.page} total={this.state.totalCount} onChange={this.changePage} /> : ''}
      </div>
    )
  }
}
export default MyComments;
MyComments.propTypes = {
  perPage: PropTypes.number,
  userInfo: PropTypes.objectOf(String),
}
